#!/bin/sh
#
# resume -- Un generador simple de currículum vítae escrito en POSIX sh.
#
# Copyright (C) 2024  Ricardo García Jiménez <ricardogj08@riseup.net>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <https://www.gnu.org/licenses/>.
#

RESUME_VERSION=1.0
RESUME_REPO=https://notabug.org/ricardogj08/resume

# Imprime mensajes de errores.
error() {
  printf '%s.\n' "$1" >&2
  exit 1
}

# Convierte un archivo Markdown a HTML.
markdown2html() {
  smu "$1" 2>/dev/null
}

# Plantilla base para la página del cv.
template() { cat <<EOF
<!DOCTYPE html>
<html lang="${RESUME_LANG}">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta name="generator" content="resume ${RESUME_VERSION}; ${RESUME_REPO}">
  <title>${RESUME_TITLE}</title>
  <link rel="stylesheet" href="${RESUME_CSS}">

  <style>
    .markdown-body {
      box-sizing: border-box;
      min-width: 200px;
      max-width: 980px;
      margin: 0 auto;
      padding: 45px;
    }

    @media (max-width: 767px) {
      .markdown-body {
        padding: 15px;
      }
    }
  </style>
</head>
<body class="markdown-body">
  $(markdown2html src/resume.md)
</body>
</html>
EOF
}

# Convierte un archivo HTML a PDF.
html2pdf() {
  wkhtmltopdf \
    --margin-top 0 \
    --margin-right 0 \
    --margin-bottom 0 \
    --margin-left 0 \
    --enable-local-file-access \
    "$1" "$2"
}

# Imprime un mensaje de ayuda.
shelp() { printf '%s' "\
resume ${RESUME_VERSION} - A simple resume generator written in POSIX sh.

Synopsis:
  resume [OPTION]

Options:
  -b - Build resume.
"
exit 0
}

main() {
  command -v smu >/dev/null ||
    error "'smu' is not installed"

  command -v wkhtmltopdf >/dev/null ||
    error "'wkhtmltopdf' is not installed"

  mkdir -p src docs ||
    error "Curriculum directories cannot be created"

  # shellcheck source=/dev/null
  [ -r resume.cfg ] && . ./resume.cfg

  # Configuración por defecto.
  : "${RESUME_LANG:=es}"
  : "${RESUME_TITLE:=Your name}"
  : "${RESUME_CSS:=https://cdnjs.cloudflare.com/ajax/libs/github-markdown-css/5.8.1/github-markdown.min.css}"

  template > docs/index.html

  cd docs || error "Can't access the 'docs' directory"

  html2pdf \
    index.html \
    "$(printf '%s' "${RESUME_TITLE}" | tr '[:blank:]' '-').pdf"
}

[ "$1" = -b ] || shelp && main
